//
//  MyPinDanViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/16.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MyPinDanViewController.h"
#import "MyPinDanCell.h"
#import "MyPinDanData.h"
#import "MyPinDanDetailViewController.h"
#define  INTERVAL kWidth/2.0
@interface MyPinDanViewController ()<UITableViewDelegate,UITableViewDataSource,DoThingsOnClickBtn>
{
    NSInteger _pageIndex;
    NSInteger _selectedCtl;
    UIView *_lineView;
    UIImageView *_imageView;
    UILabel *_tipLbl;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation MyPinDanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageIndex=1;
    self.view.backgroundColor=[UIColor whiteColor];
    self.dataSource=[NSMutableArray array];
    [self setUpTableView];
    [self setUpBgView];
    [self setUpSegmentControl];
    [self setUpLineView];
}
#pragma mark--创建没有拼单活动
-(void)setUpBgView
{
    _imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"no_spell_order"]];
    _imageView.center=self.view.center;
    _imageView.hidden=YES;
    _imageView.bounds=CGRectMake(0, 5, 80, 80);
    [self.view addSubview:_imageView];
    
    _tipLbl=[[UILabel alloc]init];
    _tipLbl.center=CGPointMake(_imageView.center.x, _imageView.center.y+40+20);
    _tipLbl.bounds=CGRectMake(0, 0, 110, 30);
    _tipLbl.text=@"目前没有拼单";
    _tipLbl.textColor=GRAYCOLOR;
    _tipLbl.hidden=YES;
    [self.view addSubview:_tipLbl];
}

#pragma mark--小蓝条
-(void)setUpLineView
{
    _lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 64+30, INTERVAL, 1)];
    _lineView.backgroundColor=BLUECOLOR;
    [self.view addSubview:_lineView];
}
#pragma mark---选择条
-(void)setUpSegmentControl
{
    for (int i=0; i<2; i++) {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(i*INTERVAL,64,INTERVAL,30)];
        btn.backgroundColor=[UIColor whiteColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:15];
        if (i==0)
        {
          [btn setTitle:@"已发布" forState:UIControlStateNormal];
          [btn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
          btn.tag=1;
          _selectedCtl=btn.tag;
        }else
        {
          btn.tag=2;
          [btn setTitle:@"已完成" forState:UIControlStateNormal];
        }
        
        [btn addTarget:self action:@selector(clickOnControl:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
}
-(void)clickOnControl:(UIButton *)btn
{
    if (_selectedCtl==btn.tag)
    {
        return;
    }
    UIButton *lastBtn=[self.view viewWithTag:_selectedCtl];
    [lastBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
    [UIView animateWithDuration:0.1 animations:^{
        _lineView.frame=CGRectMake(btn.frame.origin.x, btn.frame.origin.y+30, INTERVAL, 1);
    }];
    _selectedCtl=btn.tag;
    [self getDataWithSpellStatus:[NSString stringWithFormat:@"%ld",(long)_selectedCtl]];
    
}
#pragma mark--表
-(void)setUpTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 31, kWidth, kHeight-31) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.rowHeight=330;
    _tableView.backgroundColor=LIGHTGRAY;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addTheMoreData)];
    [_tableView registerNib:[UINib nibWithNibName:@"MyPinDanCell" bundle:nil]forCellReuseIdentifier:@"myPinDan"];
    [self.view addSubview:_tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // FinishStatus 0 进行中  1已完成  2 已失效     getStatus 0 未领取   getStatus  1 已领取
    MyPinDanCell *pinDan=[_tableView dequeueReusableCellWithIdentifier:@"myPinDan" forIndexPath:indexPath];
    pinDan.detailBtn.tag=indexPath.row;
    pinDan.inviteFriendsBtn.tag=indexPath.row;
    pinDan.selectionStyle=UITableViewCellSelectionStyleNone;
    MyPinDanData *data=self.dataSource[indexPath.row];
    [pinDan.tipBtn setTitle:[NSString stringWithFormat:@"%ld人",(long)data.NeedCount] forState:UIControlStateNormal];
    [pinDan.image sd_setImageWithURL:[NSURL URLWithString:data.ListImgUrl] placeholderImage:nil options:SDWebImageRetryFailed];
    pinDan.isSuccessImage.image=nil;
    pinDan.getAwardBtn.tag=data.SpellUserID;
    for (int i=0; i<data.HeadImgList.count; i++)
    {
        NSDictionary *dic=data.HeadImgList[i];
        UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(i*(30+5)+5, 10, 30, 30)];
        image.layer.cornerRadius=15;
        image.clipsToBounds=YES;
        [image sd_setImageWithURL:[NSURL URLWithString:dic[@"JoinHeadImg"]] placeholderImage:nil options:SDWebImageRetryFailed];
        [pinDan.joinView addSubview:image];
    }
    if (_selectedCtl==1 && data.FinishStatus==0)
    {
        //进行中的
        pinDan.detailBtn.hidden=NO;
        pinDan.inviteFriendsBtn.hidden=NO;
        pinDan.lineView.hidden=NO;
        pinDan.isSuccessImage.hidden=YES;
        pinDan.getAwardBtn.hidden=YES;
    }else
    {
        //已完成或者失效的
        pinDan.isSuccessImage.hidden=NO;
        pinDan.getAwardBtn.hidden=NO;
        pinDan.detailBtn.hidden=YES;
        pinDan.inviteFriendsBtn.hidden=YES;
        pinDan.lineView.hidden=YES;
        if (data.FinishStatus==1)
        {
            //成功
            pinDan.isSuccessImage.image=[UIImage imageNamed:@"spell_suc"];
            if (data.GetStatus==0)
            {
                [pinDan.getAwardBtn setTitle:@"领取奖励" forState:UIControlStateNormal];
                pinDan.getAwardBtn.enabled=YES;
            }else
            {
              [pinDan.getAwardBtn setTitle:@"已领取奖励" forState:UIControlStateNormal];
                pinDan.getAwardBtn.enabled=NO;
            }
            
        }else
        {
            //失效
            pinDan.isSuccessImage.image=[UIImage imageNamed:@"spell_err"];
           [pinDan.getAwardBtn setTitle:@"该拼单已失效" forState:UIControlStateNormal];
        }
    }
    pinDan.delegate=self;
    pinDan.title.text=data.SpellName;
    pinDan.introduce.text=data.SpellIntro;
    pinDan.remaindTime.text=[NSString stringWithFormat:@"剩余时间：%@",data.RemainderTime];
    pinDan.remainPeopleNum.text=data.RemainderPNum;
    return pinDan;
}
-(void)addTheMoreData
{
    _pageIndex++;
    [self getDataWithSpellStatus:[NSString stringWithFormat:@"%ld",(long)_selectedCtl]];
}
-(void)goToControllerWithIndexPath:(NSInteger)row
{
    MyPinDanData *data=self.dataSource[row];
    MyPinDanDetailViewController *pinDanDetail=[[MyPinDanDetailViewController alloc]init];
    pinDanDetail.hidesBottomBarWhenPushed=YES;
    pinDanDetail.spellUserId=[NSString stringWithFormat:@"%ld",(long)data.SpellUserID];
    [self.navigationController pushViewController:pinDanDetail animated:YES];
}
#pragma mark--请求数据
-(void)getDataWithSpellStatus:(NSString *)status
{
    [self.dataSource removeAllObjects];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   //http://192.168.1.107:3722/Activity/MySpell/{UserCode}/{SpellStatus}/{PageIndex}/{PageSize}/{Timestamp}/{Sign}
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSString *pageIndex=[NSString stringWithFormat:@"%ld",(long)_pageIndex];
    
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"SpellStatus":status,
                        @"PageIndex":pageIndex,
                        @"PageSize":@"5",
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Activity/MySpell/%@/%@/%@/%@/%@/%@",GETUSERCODE,status,pageIndex,@"5",timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
         [MBProgressHUD hideHUDForView:self.view];
        if (error) {
            [MBProgressHUD showError:@"连接服务器失败，请稍后再试"];
        }
        if ([responses[@"IsSuccess"]integerValue]==1)
        {
            NSArray *arr=responses[@"ReturnObject"];
            if (arr!=[NSNull null]) {

                    for (NSDictionary *dic in arr) {
                        MyPinDanData * data=[[MyPinDanData alloc]initWithDic:dic];
                        [self.dataSource addObject:data];
                    }
            }
            if (_dataSource.count>0)
            {
                _tableView.hidden=NO;
                _imageView.hidden=YES;
                _tipLbl.hidden=YES;
              [_tableView reloadData];
            }else
            {
                _tableView.hidden=YES;
                _imageView.hidden=NO;
                _tipLbl.hidden=NO;
            }
            
            [_tableView.mj_header endRefreshing];
            if(_dataSource.count < 10)
            {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else
            {
                [_tableView.mj_footer endRefreshing];
            }

        }else
        {
           [MBProgressHUD showError:responses[@"ReturnString"]];
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getDataWithSpellStatus:@"1"];
    [GeneralTool hideTabBar];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [GeneralTool showTabBar];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
